package com.exchange.controller;

import com.exchange.dto.ExchangeCodeDto;
import com.exchange.dto.OrderDto;
import com.exchange.entity.ExchangeCode;
import com.exchange.entity.Order;
import com.exchange.service.ExchangeCodeService;
import com.exchange.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/public")
@CrossOrigin(origins = "*")
public class CustomerExchangeController {
    
    @Autowired
    private ExchangeCodeService exchangeCodeService;
    
    @Autowired
    private OrderService orderService;
    
    // Endpoint for customers to enter an exchange code and get product info
    @PostMapping("/exchange")
    @PreAuthorize("permitAll")
    public ResponseEntity<?> processExchange(@RequestBody ExchangeRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        // Validate the exchange code
        ExchangeCodeDto codeDto = exchangeCodeService.findByCode(request.getCode())
                .orElse(null);
        
        if (codeDto == null) {
            response.put("success", false);
            response.put("message", "Invalid exchange code");
            return ResponseEntity.badRequest().body(response);
        }
        
        // Check if code is valid and unused
        if (!codeDto.getStatus().equals(ExchangeCode.ExchangeCodeStatus.UNUSED) || 
            (codeDto.getExpirationDate() != null && java.time.LocalDate.now().isAfter(codeDto.getExpirationDate()))) {
            response.put("success", false);
            response.put("message", "Exchange code is not valid or has expired");
            return ResponseEntity.badRequest().body(response);
        }
        
        // Return exchange code info and associated products
        response.put("success", true);
        response.put("exchangeCode", codeDto);
        // In a real implementation, we'd fetch the products associated with this exchange code
        // For now, we'll return a placeholder
        response.put("products", "Products associated with this exchange code would be returned here");
        
        return ResponseEntity.ok(response);
    }
    
    // Endpoint for customers to complete their exchange order
    @PostMapping("/exchange/complete")
    @PreAuthorize("permitAll")
    public ResponseEntity<?> completeExchange(@RequestBody CompleteExchangeRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        // Validate the exchange code
        ExchangeCodeDto codeDto = exchangeCodeService.findByCode(request.getCode())
                .orElse(null);
        
        if (codeDto == null) {
            response.put("success", false);
            response.put("message", "Invalid exchange code");
            return ResponseEntity.badRequest().body(response);
        }
        
        // Check if code is valid and unused
        if (!codeDto.getStatus().equals(ExchangeCode.ExchangeCodeStatus.UNUSED) || 
            (codeDto.getExpirationDate() != null && java.time.LocalDate.now().isAfter(codeDto.getExpirationDate()))) {
            response.put("success", false);
            response.put("message", "Exchange code is not valid or has expired");
            return ResponseEntity.badRequest().body(response);
        }
        
        // Create an order for this exchange
        Order order = new Order();
        order.setExchangeCodeId(codeDto.getId());
        order.setMerchantId(codeDto.getMerchantId());
        order.setCustomerName(request.getCustomerName());
        order.setCustomerPhone(request.getCustomerPhone());
        order.setCustomerEmail(request.getCustomerEmail());
        order.setDeliveryType(request.getDeliveryType());
        order.setShippingAddress(request.getShippingAddress());
        order.setOrderStatus(Order.OrderStatus.PENDING);
        
        OrderDto createdOrder = orderService.createOrder(order, codeDto.getMerchantId());
        
        // Mark exchange code as used
        ExchangeCode codeEntity = new ExchangeCode();
        codeEntity.setId(codeDto.getId());
        codeEntity.setStatus(ExchangeCode.ExchangeCodeStatus.USED);
        codeEntity.setUsedAt(java.time.LocalDateTime.now());
        codeEntity.setUsedBy(request.getCustomerName());
        exchangeCodeService.updateExchangeCode(codeDto.getId(), codeEntity);
        
        response.put("success", true);
        response.put("message", "Exchange completed successfully");
        response.put("order", createdOrder);
        
        return ResponseEntity.ok(response);
    }
    
    // Endpoint for customers to track their order status
    @GetMapping("/order/track/{orderNumber}")
    @PreAuthorize("permitAll")
    public ResponseEntity<?> trackOrder(@PathVariable String orderNumber) {
        return orderService.findByOrderNumber(orderNumber)
                .map(order -> {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", true);
                    response.put("order", order);
                    return ResponseEntity.ok(response);
                })
                .orElse(ResponseEntity.notFound().build());
    }
    
    // Request classes
    public static class ExchangeRequest {
        private String code;
        
        public String getCode() { return code; }
        public void setCode(String code) { this.code = code; }
    }
    
    public static class CompleteExchangeRequest {
        private String code;
        private String customerName;
        private String customerPhone;
        private String customerEmail;
        private Order.DeliveryType deliveryType;
        private String shippingAddress;
        
        public String getCode() { return code; }
        public void setCode(String code) { this.code = code; }
        
        public String getCustomerName() { return customerName; }
        public void setCustomerName(String customerName) { this.customerName = customerName; }
        
        public String getCustomerPhone() { return customerPhone; }
        public void setCustomerPhone(String customerPhone) { this.customerPhone = customerPhone; }
        
        public String getCustomerEmail() { return customerEmail; }
        public void setCustomerEmail(String customerEmail) { this.customerEmail = customerEmail; }
        
        public Order.DeliveryType getDeliveryType() { return deliveryType; }
        public void setDeliveryType(Order.DeliveryType deliveryType) { this.deliveryType = deliveryType; }
        
        public String getShippingAddress() { return shippingAddress; }
        public void setShippingAddress(String shippingAddress) { this.shippingAddress = shippingAddress; }
    }
}